<template>
    <el-card shadow="never">
        <template #header>
            <div class="flex justify-between">
                <span class="text-sm">订单统计</span>
                <div>
                    <el-check-tag v-for="(item,index) in options" :key="index" :checked="current == item.value" style="margin-right: 8px" @click="handleChose(item.value)">{{item.text}}</el-check-tag>
                </div>
            </div>
        </template>
        <div id="chart" style="width:100%;height:300px;" ref="el">
        </div>
    </el-card>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue"
import * as echarts from 'echarts';
import { getStatistics3 } from '~/api/index.js'
import { useResizeObserver } from '@vueuse/core'

const current = ref('week')
const options = [
    {
        text: '近一个月',
        value: 'month'
    },
    {
        text: '近一周',
        value: 'week'
    },
    {
        text: '近24小时',
        value: 'hour'
    }
]

const handleChose = (type) => {
    current.value = type
    getData()
}
let myChart = null
onMounted(() => {
    let chartDom = document.getElementById('chart');
    if (chartDom) {
        myChart = echarts.init(chartDom);
        getData()
    }
})

// 在页面被销毁之前，进行销毁echarts实例
onBeforeUnmount(() => {
    if (myChart) echarts.dispose(myChart)
})

// 获取数据的方法
function getData () {
    let option = {
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [120, 200, 150, 80, 70, 110, 130],
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }
        ]
    };
    myChart.showLoading()
    getStatistics3(current.value).then(res => {
        option.xAxis.data = res.x
        option.series.data = res.y
        option && myChart.setOption(option);
    }).finally(() => {
        myChart.hideLoading()
    })
}

const el = ref(null)

// 调用VueUse库里面的方法，监测页面的放大缩小，同时设置echarts实例的大小
useResizeObserver(el, (entries) => {
    if (myChart) {
        myChart.resize()
    }
})
</script>